﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;

namespace TopShooter                                                                
{
	public interface IAnimated
	{
		void SetFrame(Frame frame);
	}

	public struct Frame
	{
		public float Rotation;
		public Vector2 Offset;
		public float TimeDelta;

		public Frame(float rotation, Vector2 offset, float timeDelta)
		{
			Rotation = rotation;
			Offset = offset;
			TimeDelta = timeDelta;

		}
	}

	public class Animation : Activity
	{
		public IAnimated Target;
		public int CurrentFrameIndex = 0;
		public Frame PreviousFrame;
		public Frame CurrentFrame;
		public float CurrentTimeElapsed;

		public List<Frame> Frames;

		public Animation(IAnimated target, List<Frame> frames)
		{
			Target = target;
			Frames = frames;
		}

		protected override void _OnStarted()
		{
			base._OnStarted();
			Target.SetFrame(Frames[0]);

			CurrentFrameIndex = 1;
			PreviousFrame = Frames[0];
			CurrentFrame = Frames[1];
			CurrentTimeElapsed = 0;
		}

		protected override bool OnUpdate(float timeDelta)
		{
			CurrentTimeElapsed += timeDelta;

			while (CurrentTimeElapsed > CurrentFrame.TimeDelta)
			{
				CurrentTimeElapsed -= CurrentFrame.TimeDelta;
				CurrentFrameIndex++;

				if (CurrentFrameIndex >= Frames.Count)
				{
					return true;
				}
				PreviousFrame = CurrentFrame;
				CurrentFrame = Frames[CurrentFrameIndex];
			}

			float nTime = CurrentTimeElapsed / CurrentFrame.TimeDelta;
			float invNTime = (CurrentFrame.TimeDelta - CurrentTimeElapsed) / CurrentFrame.TimeDelta;

			Frame f = new Frame();
			f.Rotation = (invNTime * PreviousFrame.Rotation) + (nTime * CurrentFrame.Rotation);
			f.Offset = (invNTime * PreviousFrame.Offset) + (nTime * CurrentFrame.Offset);

			Target.SetFrame(f);

			return false;
		}

		protected override void _OnEnded()
		{
			base._OnEnded();
			Target.SetFrame(new Frame());
		}

	}
}
